package com.kf5.sdk

import android.app.Activity
import android.util.Log
import com.dhy.xintent.Flow
import com.dhy.xintent.Waterfall
import com.dhy.xintent.toast
import com.kf5.sdk.system.entity.Field
import com.kf5.sdk.system.init.UserInfoAPI
import com.kf5.sdk.system.internet.HttpRequestCallBack
import com.kf5.sdk.system.utils.SPUtils
import com.kf5.sdk.system.utils.SafeJson

interface ILoginKF5 {
    companion object {
        private const val KF5_TAG = "kf5测试"
    }

    val activity: Activity

    fun loginKF5(callBack: ((success: Boolean) -> Unit)? = null) {
        showProgressDialog()
        Waterfall.flow {
            loginUser(this)
        }.flow {
            createUser(this)
        }.onEnd {
            dismissProgressDialog()
            callBack?.invoke(getPreResult())
        }
    }

    fun showProgressDialog()
    fun dismissProgressDialog()
    fun getUserInfo(): Map<String, String>

    private fun loginUser(flow: Flow) {
        UserInfoAPI.getInstance().loginUser(getUserInfo(), getHttpCallBack(flow))
    }

    private fun createUser(flow: Flow) {
        UserInfoAPI.getInstance().createUser(getUserInfo(), getHttpCallBack(flow))
    }

    fun parseResult(flow: Flow, result: String) {
        val jsonObject = SafeJson.parseObj(result)
        val resultCode = SafeJson.safeInt(jsonObject, "error")
        if (resultCode == 0) {
            val dataObj = SafeJson.safeObject(jsonObject, Field.DATA)
            val userObj = SafeJson.safeObject(dataObj, Field.USER)
            if (userObj != null) {
                val userToken = userObj.getString(Field.USERTOKEN)
                val id = userObj.getInt(Field.ID)
                SPUtils.saveUserToken(userToken)
                SPUtils.saveUserId(id)
                flow.end(true)
            }
        } else {
            //{"error":10050,"message":"用户不存在","data":{}}
            if (resultCode == 10050) flow.next()
            else {
                flow.end(false)
                Log.e(KF5_TAG, result)
                handleError(result)
            }
        }
    }

    private fun getHttpCallBack(flow: Flow): HttpRequestCallBack {
        return object : HttpRequestCallBack {
            override fun onSuccess(result: String) {
                activity.runOnUiThread {
                    parseResult(flow, result)
                }
            }

            override fun onFailure(result: String) {
                Log.e(KF5_TAG, result)
                activity.runOnUiThread {
                    dismissProgressDialog()
                    handleError(result)
                    flow.end(false)
                }
            }
        }
    }

    fun handleError(result: String) {
        val jsonObject = SafeJson.parseObj(result)
        if (jsonObject != null) {
            val msg = jsonObject.optString("message")
            if (msg.isNotEmpty()) showErrorTip(ErrorType.SERVER, msg)
            else showErrorTip(ErrorType.UNKNOWN, "未知错误")
        } else {
            if (result.contains("云客服平台已过期")) {
                showErrorTip(ErrorType.EXPIRED, "云客服已过期，请联系管理员")
            } else {
                showErrorTip(ErrorType.UNKNOWN, "未知错误")
            }
        }
    }

    fun showErrorTip(errorType: ErrorType, tip: String) {
        activity.toast(tip)
    }
}

enum class ErrorType {
    /**
     * error message from server
     * */
    SERVER,

    /**
     * service expired
     * */
    EXPIRED,

    /**
     * all unknown error
     * */
    UNKNOWN
}